package com.snail.sell.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 21:53 2017/12/8
 * @Modified By:
 **/
@RestController
@RequestMapping("/wechat")
@Slf4j
public class WeixinController {

    @GetMapping("/auth")
    public void auth(@RequestParam("code") String code){

        log.info("进入authentic方法 code={}",code);


        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx0807f8636ccc9325&secret=3cce0fb303517513354b12554013ecaf&code="
                +code+"&grant_type=authorization_code";

        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url,String.class);
        log.info("result, result={}",result);
    }
    /*private static String token = "root";
*/
    /*@GetMapping("/auth")
    public String auth(@RequestParam("signature") String signature,
                     @RequestParam("timestamp") String timestamp,
                     @RequestParam("nonce") String nonce,
                       @RequestParam("echostr") String echostr) {

        *//*System.out.println("++++++++++" );
      log.info("code+++ code={}", code);*//*
        boolean result = false;

        // 对token、timestamp和nonce按字典序排序
        String[] array = new String[]{token, timestamp, nonce};
        Arrays.sort(array);

        // 将三个参数字符拼接成一个字符串
        String str = array[0].concat(array[1]).concat(array[2]);

        String sha1Str = null;
        try {
            // 对拼接后的字符串进行sha1加密
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.getBytes());
            sha1Str = byte2str(digest);
        }
        catch(Exception e) {
        }

        if(sha1Str != null &&  sha1Str.equals(signature)) {

            return echostr;
        }

        return null;


    }



    public static String byte2str(byte[] array) {
        StringBuffer hexstr = new StringBuffer();
        String shaHex="";
        for(int i = 0; i < array.length; i++) {
            shaHex = Integer.toHexString(array[i] & 0xFF);
            if(shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }
        return hexstr.toString();
    }*/
}
